//
//  CSYPictureSeletedViewController.swift
//  CSYMicroBlockSina
//
//  Created by 姚彦兆 on 15/11/19.
//  Copyright © 2015年 姚彦兆. All rights reserved.
//

import UIKit

private let pictureWidth : CGFloat = (screen_Width - 5 * cellMargin) / 4

private let maxImageCount : NSInteger = 4

private let reuseIdentifier = "Cell"

class CSYPictureSeletedViewController: UICollectionViewController {

    //设置数据源数组
    
    lazy var pictureBox : [UIImage] = [UIImage]()
    
    init(){
        
        let layout : UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = cellMargin
        
        layout.minimumLineSpacing = cellMargin
        
        layout.itemSize = CGSizeMake(pictureWidth, pictureWidth)
        
        layout.sectionInset = UIEdgeInsetsMake(cellMargin, cellMargin, 0, cellMargin)
        
        super.init(collectionViewLayout: layout)
        
    }
    
    private func caculateItemSize() -> CGSize{
    
        let width : CGFloat = (screen_Width - 5 * cellMargin) / 4
        
        return CGSizeMake(width, width)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(CSYPictureSeletedCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        self.collectionView?.backgroundColor = UIColor(white: 0.85, alpha: 1)
        
        // Do any additional setup after loading the view.
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        
        let flag = (pictureBox.count == maxImageCount) ? 0 : 1
        
        return pictureBox.count + flag
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CSYPictureSeletedCell
    
        cell.delegate = self
        
        cell.backgroundColor = UIColor(white: 0.97, alpha: 1)
        
        if indexPath.item == pictureBox.count{
        
            cell.image = nil
        
        }else{
        
            cell.image = pictureBox[indexPath.item]
        
        }
        
        return cell
    }

}

extension CSYPictureSeletedViewController : CSYPictureSeletedCellDelegate{

    func clickAddBtn(targetCell: CSYPictureSeletedCell) {
        
        if targetCell.image != nil{
        
            print("已经有图片")
        
            return
            
        }
        
        print("++点击了添加图片按钮++")
        
        //添加图片需要使用系统的图片选择器
        let picturePick = UIImagePickerController()
        
        picturePick.delegate = self
        
        picturePick.allowsEditing = true
        
        presentViewController(picturePick, animated: true, completion: nil)
    }

    func clickDeleteBtn(targetCell: CSYPictureSeletedCell) {
        
        print("--点击了删除图片按钮--")
        
        let indexPath : NSIndexPath = (collectionView?.indexPathForCell(targetCell))!
        
        pictureBox.removeAtIndex(indexPath.item)
        
        UIView.animateWithDuration(0.75, animations: { () -> Void in
            
            targetCell.alpha = 0
            
            }) { (_) -> Void in
                
                targetCell.alpha = 1
                
                self.collectionView?.reloadData()
                
        }
        
    }

}

extension CSYPictureSeletedViewController : UIImagePickerControllerDelegate , UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
     
        pictureBox.append(image)
        
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
}


@objc protocol CSYPictureSeletedCellDelegate : NSObjectProtocol{

    optional func clickAddBtn( targetCell : CSYPictureSeletedCell )
    
    optional func clickDeleteBtn( targetCell : CSYPictureSeletedCell )

}


class CSYPictureSeletedCell : UICollectionViewCell{

    var image : UIImage? {
    
        didSet{
        
            delete_Btn.hidden = (image == nil)
        
            if image != nil {
            
                add_Btn.setBackgroundImage(image, forState: UIControlState.Normal)
            
            }else{

                add_Btn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            
            }
            
        }
    
    }
    
    weak var delegate : CSYPictureSeletedCellDelegate?
    
    @objc private func clickAddButton(){
    
        delegate?.clickAddBtn!(self)
    
    }
    
    @objc private func clickDeleteButton(){
    
        delegate?.clickDeleteBtn!(self)
    
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setUpUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI(){
    
        contentView.addSubview(add_Btn)
        
        contentView.addSubview(delete_Btn)
        
        add_Btn.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self.snp_edges)
            
        }
        
        delete_Btn.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(add_Btn.snp_top)
            
            make.right.equalTo(add_Btn.snp_right)
            
        }
        
        add_Btn.addTarget(self, action: "clickAddButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        delete_Btn.addTarget(self, action: "clickDeleteButton", forControlEvents: UIControlEvents.TouchUpInside)
    
    }
    
    lazy var add_Btn = UIButton(title: "", titleColor: UIColor(white: 0.95, alpha: 1), image: "", backImage: "compose_pic_add", fontSize: 0)
    
    lazy var delete_Btn = UIButton(title: "", titleColor: nil, image: "", backImage: "compose_photo_close", fontSize: 0)

}
























